package com.demo.service.impl;


import com.demo.annotation.DataSource;
import com.demo.dto.User;
import com.demo.service.UserService;
import com.mapper.UserServiceMapper;
import com.demo.thread.TestThread;
import com.demo.util.CommonsUtil;
import com.demo.util.RedisUtil;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 实现测试接口
 * @DataSource 可以修改类的默认数据源
 */
@Service
@DataSource("mysqlTwo")
public class UserServiceImpl implements UserService {
    private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private UserServiceMapper userServiceMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    /**
     * @DataSource 可以修改方法的默认数据源
     * @param userId
     * @return
     */
    @Override
    @DataSource("mysqlOne")
    public int deleteUserById(Long userId) {
        //测试日志是否可以打印
        logger.info("UserServiceImpl deleteUserById  param: "+userId);

        //测试多线程
        User detail=new User();
        detail.setId(userId);
        taskExecutor.execute(new TestThread(userServiceMapper,detail));

        //测试redis
        if(redisUtil.hasKey(userId.toString())){
            return Integer.parseInt(redisUtil.get(userId.toString()).toString());
        }else{
            int result=userServiceMapper.deleteUserById(userId);
            //后台主要是redis存取值 过期时间10秒暂时
            redisUtil.set(userId.toString(),result, CommonsUtil.REDIS_TIME);
            return result;
        }
    }

    @Override
    public User selectUserByAccountName(String accountName) {
        List<User> list=  userServiceMapper.selectUserByAccountName(accountName);
        if (!CollectionUtils.isEmpty(list)){
            return list.get(0);
        } else {
            return null;
        }
    }

    @Override
    public List<User> selectUsers() {
        return userServiceMapper.selectUsers();
    }

    @Override
    public int insertUser(User user) {
        return userServiceMapper.insertUser(user);
    }

    @Override
    public User doUserLogin(User user) {
        List<User> list =  userServiceMapper.selectUserByAccountName(user.getAccountName());
        if(list.size() == 0){
            return null;
        }else{
            if(user.getPassword().equals(list.get(0).getPassword())){
                return list.get(0);
            }else{
                return null;
            }
        }
    }
}
